define([
  'dates', 'template7compile', 'apiClient'
], function(dates, template7compile, apiClient) {
  var self = {};
  self.beforeInit = function() {
    self.dates = dates.get();
  }
  function courseFormat(courses) {
    _.map(courses, function(course) {
      var start = moment(course.startTime, moment.ISO_8601);
      return {
        id: course.courseId,
        name: course.courseNname,
        className: course.courseClass,
        classroom: course.classroomName,
        time: moment(course.startTime, moment.ISO_8601).format('H:mm') + '-' + moment(course.endTime, moment.ISO_8601).format('H:mm')
      };
    })
  }
  self.init = function(e) {
    document.title = "课程表";
    // load dates template
    template7compile.compile('#schedule script#dates', {
      dates: self.dates
    }, '#schedule .days');
    // T.B.D. how to get today's index
    var todayIndex = dates.getIndex(self.dates, new Date());
    // scroll to today when pressing <a> tab '今'
    $$('.today').on('click', function() {
      var todayItem = $('.days')[0].children[todayIndex];
      todayItem.click();
      $('.days').scrollLeft(todayItem.offsetLeft);
      // T.B.D. load corresponding data
    })
    // selected effect of pressing day
    $$('a.tab-link').on('click', function() {
      $$('.currentDay').removeClass('currentDay');
      $$(this).addClass('currentDay');
      apiClient.get('/teacher/courseFields/list.do', {
        searchDate: this.id,
        page: 1,
        size: 20
      }, function(data, status, xhr) {
        if (status.toString() == '200') {
          template7compile.compile('#schedule script#lessons', {
            lessons: courseFormat(data.items)
          }, '#schedule .page-content');
        }
      }, function(xhr, status) {})
    })
    // event of pushing course detail
    $$('.course-cell').on('click', function() {
      var courseId = this.id;
      mainView.router.load({
        url: '<%= purl ' teacher_side / course / detail ' %>' ,
        query: {
          courseId: courseId
        }
      })
    })
  }
  self.afterAnime = function() {
    // select today's date at first
    $$('.today').click();
  }
  return self;
})
